'use strict';
/**
 * Created by FreezeSoul on 2016/1/20.
 */
define([
    "app/core/base",
    "app/core/util",
    "../commonMeta",
    "jquery",
    "underscore",
    'JSONParse',
    'loglevel',
    'momentjs',
    'pikaday'
], function (Chart, Util, Meta, $, _, JSON, log, moment, Pikaday) {
    //TODO:自定义组件属性
    var property = {
        config: "property",
        option: [
            {
                group: '基础',
                id: 'TimeTitleInfo',
                name: '标题信息',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'TimeTitleInfo',
                tooltip: '标题信息'
            },
            {
                group: '基础',
                id: 'IsRangeMode',
                name: '范围选择',
                enable: false,
                type: 'checked',
                value: true,
                default: true,
                link: 'IsRangeMode',
                tooltip: '范围选择'
            },
            {
                group: '基础',
                id: 'StartDateType',
                name: '开始时间',
                enable: false,
                type: 'select',
                value: 'today',
                default: 'today',
                data: [
                    {
                        value: 'today',
                        text: '今天'
                    },
                    {
                        value: 'yestoday',
                        text: '昨天'
                    },
                    {
                        value: 'tomorrow',
                        text: '明天'
                    },
                    {
                        value: 'lastmonth',
                        text: '上月初'
                    },
                    {
                        value: 'thismonth',
                        text: '本月初'
                    },
                    {
                        value: 'nextmonth',
                        text: '下月初'
                    },
                    {
                        value: 'lastweek',
                        text: '上周初'
                    },
                    {
                        value: 'thisweek',
                        text: '本周初'
                    },
                    {
                        value: 'nextweek',
                        text: '下周初'
                    }
                ],
                link: 'StartDateType',
                tooltip: '开始时间选择'
            },
            {
                group: '基础',
                id: 'EndDateType',
                name: '开始时间',
                enable: false,
                type: 'select',
                value: 'tomorrow',
                default: 'tomorrow',
                data: [
                    {
                        value: 'today',
                        text: '今天'
                    },
                    {
                        value: 'yestoday',
                        text: '昨天'
                    },
                    {
                        value: 'tomorrow',
                        text: '明天'
                    },
                    {
                        value: 'lastmonth',
                        text: '上月初'
                    },
                    {
                        value: 'thismonth',
                        text: '本月初'
                    },
                    {
                        value: 'nextmonth',
                        text: '下月初'
                    },
                    {
                        value: 'lastweek',
                        text: '上周初'
                    },
                    {
                        value: 'thisweek',
                        text: '本周初'
                    },
                    {
                        value: 'nextweek',
                        text: '下周初'
                    }
                ],
                link: 'EndDateType',
                tooltip: '结束时间选择'
            },
            {
                group: '基础',
                id: 'TimeTitleColor',
                name: '标题颜色',
                enable: false,
                type: 'color',
                value: '#000000',
                default: '#000000',
                link: 'TimeTitleColor',
                tooltip: '标题颜色'
            },
            {
                group: '基础',
                id: 'BackgroundColor',
                name: '背景颜色',
                enable: false,
                type: 'color',
                value: 'transparent',
                default: 'transparent',
                link: 'BackgroundColor',
                tooltip: '背景颜色，透明色transparent'
            },
            {
                group: '基础',
                id: 'ButtonTheme',
                name: '按钮样式',
                enable: false,
                type: 'select',
                value: 'default',
                default: 'default',
                data: [
                    {value: 'default', text: 'default'},
                    {value: 'danger', text: 'danger'},
                    {value: 'warning', text: 'warning'},
                    {value: 'primary', text: 'primary'},
                    {value: 'success', text: 'success'},
                    {value: 'info', text: 'info'}
                ],
                link: 'ButtonTheme',
                tooltip: '按钮样式'
            },
            {
                group: '事件',
                id: 'DatePickerClick',
                name: '日期过滤事件',
                enable: true,
                type: 'pivotEvent',
                value: {
                    Event: "DatePickerClick",
                    Params: [
                        {Value: "StartDate", Name: "开始日期"},
                        {Value: "EndDate", Name: "结束日期"}
                    ]
                },
                tooltip: '日期过滤事件，钻取设置'
            }
        ].concat($.extend(true, [], Meta.commonProperties)),
        MapOption: function (option) {
            Util.linkOption(this.option, option);
        }
    };

    var datepicker = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._element = null;
            this._container = null;
            this._option = {
                Series: [],
                Events: [],
                Extend: $.extend(true, {}, property),
                Option: {
                    uuid: '',
                    class: '',
                    display: true,
                    IsRangeMode: true,
                    TimeTitleInfo: "时间范围选择",
                    StartDateType: "today",
                    EndDateType: "tomorrow",
                    BackgroundColor: 'transparent',
                    TimeTitleColor: '#000000',
                    ButtonTheme: 'default',
                    initScript: '',
                    disposeScript: ''
                }
            };
        },
        init: function (element) {
            try {
                this._container = element;
            } catch (e) {
                log.error(e);
            }
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                Util.deepMapOption(property, this._option.Extend, this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        _render: function (option) {
            $(this._container).empty();

            var $dateElement = $('<div style="text-align:center;width: 100%;height: 100%;"><div style="margin: 15px;display:inline-block;">' +
                '<div class="title_datapicker_div" style="margin: 5px;font-size: 16px;font-weight: bold;text-align: left;color: rgb(0, 0, 0); float: left;line-height: 26px;"></div>' +
                '<div class="start_datepicker_div" style="float:left;margin: 5px;"><input type="text" class="start_datepicker"/></div>' +
                '<div class="end_datepicker_div" style="float:left;margin: 5px;"><input type="text" class="end_datepicker"/></div>' +
                '<div class="btn_div" style="float:left;margin: 5px;"><button class="btn btn-sm">确定</button></div>' +
                '</div></div>');

            if (!option.IsRangeMode) {
                $dateElement.find(".end_datepicker_div").hide();
            }
            if (option.TimeTitleInfo) {
                $dateElement.find(".title_datapicker_div").show().text(option.TimeTitleInfo);
            } else {
                $dateElement.find(".title_datapicker_div").hide();
            }
            if (option.BackgroundColor) {
                $dateElement.css("background", option.BackgroundColor);
            }
            if (option.TimeTitleColor) {
                $dateElement.find(".title_datapicker_div").css("color", option.TimeTitleColor);
            }
            if (option.ButtonTheme) {
                $dateElement.find("button.btn").addClass("btn-" + option.ButtonTheme);
            } else {
                $dateElement.find("button.btn").addClass("btn-default");
            }

            var i18nCn = {
                previousMonth: '前一个月',
                nextMonth: '后一个月',
                months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                monthsShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
                weekdays: ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
                weekdaysShort: ['日', '一', '二', '三', '四', '五', '六']
            };

            //计算时间
            this._StartDateTime = this._computeDate(option.StartDateType);
            this._EndDateTime = this._computeDate(option.EndDateType);

            var values = this._pivotValues("DatePickerClick");
            if (values && values.length > 0) {
                var value1 = _.findWhere(values, {Value: "StartDate"});
                if (value1 && value1.ParamValue) {
                    this._StartDateTime = value1.ParamValue;
                }
                var value2 = _.findWhere(values, {Value: "EndDate"});
                if (value2 && value2.ParamValue) {
                    this._EndDateTime = value2.ParamValue;
                }
            }

            var startPikaday = new Pikaday({
                field: $dateElement.find(".start_datepicker")[0],
                i18n: i18nCn
            });

            startPikaday.setDate(!this._StartDateTime ? moment(new Date()).format('YYYY-MM-DD') : this._StartDateTime);

            var endPikaday = new Pikaday({
                field: $dateElement.find(".end_datepicker")[0],
                i18n: i18nCn
            });
            endPikaday.setDate(!this._EndDateTime ? moment(new Date()).format('YYYY-MM-DD') : this._EndDateTime);

            $dateElement.appendTo(this._container);
            this._bindEvent($dateElement);

            //Util.setCommonMeta(this, this._container, this._option.Option);
            //Util.initChartLifeTime(this, this._container, this._option.Option);

            return $dateElement;
        },
        _computeDate: function (dateType) {
            var date = new Date();
            if (dateType == "today") {
                date = new Date();
            } else if (dateType == "yestoday") {
                date.setDate(date.getDate() - 1);
            } else if (dateType == "tomorrow") {
                date.setDate(date.getDate() + 1);
            } else if (dateType == "lastmonth") {
                date = new Date(date.getFullYear(), date.getMonth(), 1);
                date.setMonth(date.getMonth() - 1);
            } else if (dateType == "thismonth") {
                date = new Date(date.getFullYear(), date.getMonth(), 1);
            } else if (dateType == "nextmonth") {
                date = new Date(date.getFullYear(), date.getMonth(), 1);
                date.setMonth(date.getMonth() + 1);
            } else if (dateType == "lastweek") {
                date.setDate(date.getDate() - 7);
                var day = date.getDay(),
                    diff = date.getDate() - day + (day == 0 ? -6 : 1);
                date = new Date(date.setDate(diff));
            } else if (dateType == "thisweek") {
                var day = date.getDay(),
                    diff = date.getDate() - day + (day == 0 ? -6 : 1);
                date = new Date(date.setDate(diff));
            } else if (dateType == "nextweek") {
                date.setDate(date.getDate() + 7);
                var day = date.getDay(),
                    diff = date.getDate() - day + (day == 0 ? -6 : 1);
                date = new Date(date.setDate(diff));
            } else {
                date = new Date();
            }
            return moment(date).format('YYYY-MM-DD');
        },
        _pivotValues: function (eventName) {
            var _this = this;
            var values = [];
            var registerEvent = _.findWhere(_this._option.Events, {Event: eventName});
            if (registerEvent) {
                values = registerEvent.Params;
                if (this._layout && this._layout.getParams) {
                    var params = this._layout.getParams();
                    $.each(params, function (i, param) {
                        var value = _.findWhere(values, {ParamName: param.ParamName});
                        if (value) {
                            value.ParamValue = param.ParamValue;
                        }
                    });
                }
            }
            return values;
        },
        _bindEvent: function (element) {
            var _this = this;
            $(element).find("button.btn").on("click", function (e) {
                if (_this._layout
                    && _this._layout.navigate
                    && _this._option.Events
                    && _this._option.Events.length > 0) {

                    var registerEvent = _.findWhere(_this._option.Events, {Event: "DatePickerClick"});
                    if (registerEvent) {
                        var pageId = registerEvent.PageId;
                        var params = registerEvent.Params;
                        var args = [];
                        var sParam = _.findWhere(params, {Value: "StartDate"});
                        if (sParam && sParam.ParamName) {
                            args.push({
                                ParamName: sParam.ParamName,
                                ParamValue: $(element).find(".start_datepicker").val()
                            });
                        }
                        var eParam = _.findWhere(params, {Value: "EndDate"});
                        if (eParam && eParam.ParamName) {
                            args.push({
                                ParamName: eParam.ParamName,
                                ParamValue: $(element).find(".end_datepicker").val()
                            });
                        }
                        _this._layout.navigate(pageId, args);

                    }
                    e.preventDefault();
                }
            });
        },
        example: function () {
            try {
                var exampleOption = {
                    IsRangeMode: true,
                    TimeTitleInfo: "时间范围选择",
                    StartDateType: "today",
                    EndDateType: "tomorrow",
                    BackgroundColor: 'transparent',
                    TimeTitleColor: '#000',
                    ButtonTheme: 'default'
                };
                this._element = this._render(exampleOption);
            } catch (e) {
                log.error(e);
            }
        },
        _bindData: function (data) {
            //TODO:待实现绑定支持
        },
        setData: function (data) {
            try {
                this._readProperty();
                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                ) {
                    this._bindData(data);
                }
                this._element = this._render(this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            try {
                this._readProperty();
            } catch (e) {
                log.error(e);
            }
            return this._option;
        },
        setTheme: function (theme) {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                $(this._element).remove();
                //Util.disposeChartLifeTime(this, this._container, this._option.Option);

            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return this._element;
        },
        getChart: function () {
            return this._element;
        }
    });

    return {
        Chart: datepicker,
        Property: property
    };
});